package com.llgz.hotelmanageapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.llgz.hotelmanageapi.common.CommonResult;
import com.llgz.hotelmanageapi.pojo.DO.UserInfo;
import com.llgz.hotelmanageapi.pojo.DTO.LoginDTO;
import com.llgz.hotelmanageapi.shiro.JWTToken;
import com.llgz.hotelmanageapi.utils.JWTUtil;
import com.llgz.hotelmanageapi.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author Bernie_fang
 * @Description:
 * @create 2021/7/23 15:41
 **/
@Service
public class CommonServiceImpl {


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserInfoServiceImpl userInfoService;


    public CommonResult login(LoginDTO loginDTO) {
        // 判空
        if (StringUtils.isEmpty(loginDTO.getUsername())) {
            // throw new IllegalArgumentException("用户名不能为空");
            return CommonResult.errorResponse("用户名不能为空");
        }
        if (StringUtils.isEmpty(loginDTO.getPassword().trim())) {
            return CommonResult.errorResponse("密码不能为空");
        }
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>();
        wrapper.eq("username", loginDTO.getUsername());
        UserInfo userInfo = userInfoService.getOne(wrapper);

        if (userInfo == null) {
            return CommonResult.errorResponse("用户名不存在！");
        }

        if (!userInfo.getPassword().equals(loginDTO.getPassword())) {
            // 密码错误
            return CommonResult.errorResponse("密码错误！");
        }
        String token = new String();
        try {
            //生成签名
            token = JWTUtil.sign(userInfo);
            //构造JWT Token
            JWTToken jwtToken = new JWTToken(token);

            //shiro安全框架：获取subject对象
            Subject subject = SecurityUtils.getSubject();



            //设置token
            subject.login(jwtToken);
        } catch (Exception e) {
            //发生异常，说明登录失败
            return CommonResult.errorResponse("登录出错，请检查用户名、密码");
        }
        redisUtils.set("Login:"+ userInfo.getId(),userInfo,4 * 60 * 1000);
        userInfo.setPassword("******");
        //将user对象返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userInfo", userInfo);
        return CommonResult.successResponse(map);
    }

}
